package com.ifp.opengate.boot.utils;

import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.ifp.core.log.Trace;
import com.ifp.core.util.SpringContextsUtil;
import com.ifp.core.util.StringUtil;
import com.ifp.opengate.boot.bean.ValidatorForm;
import com.ifp.opengate.boot.decode.CryptoService;
import com.ifp.opengate.boot.decode.contants.DecodeContants;
import com.ifp.opengate.boot.emum.ErrorEnum;
import com.ifp.opengate.boot.exception.AccessControlException;

/**
 * <p>
 * 解密类
 * </P>
 *
 * @author zhuzh@belink.com
 * @version 0.0.1
 * @className DecodeToolDelegate
 * @sine 2020/4/23 14:31
 */
public final class DecodeToolDelegate {

    /**
     * 报文解密
     * 
     * @param content
     * @param validatorForm
     * @return
     * @throws Exception
     */
    public static Object decode(String cipher, String content, ValidatorForm validatorForm) throws Exception {
        Trace.logInfo(Trace.MODULE_FILTER, "DecodeToolDelegate start decode....");
        CryptoService cryptoService = getCryptoService(validatorForm);
        String plainText;
        // 解密服务解密
        plainText = cryptoService.decode(content, cipher, validatorForm.getParamName());
        if ("0".equals(validatorForm.getParamType())) {
            // 参数为field类型
            return plainText;
        } else if ("1".equals(validatorForm.getParamType())) {
            // 参数为List
            return JSON.parseArray(plainText, Map.class);
        }

        throw new AccessControlException(ErrorEnum.decodeError.code(),
            String.format(ErrorEnum.decodeError.msg(), validatorForm.getParamName()));
    }

    /**
     * 加密
     * 
     * @param cipher
     * @param content
     * @param validatorForm
     * @return
     * @throws Exception
     */
    public static String encode(String cipher, Object content, ValidatorForm validatorForm) throws Exception {
        Trace.logInfo(Trace.MODULE_FILTER, "DecodeToolDelegate start encode....");

        CryptoService cryptoService = getCryptoService(validatorForm);
        // 解密服务解密
        String plainText = cryptoService.encode(JSON.toJSONString(content), cipher, validatorForm.getParamName());
        return plainText;

    }

    /**
     * 获取加密服务
     * 
     * @param validatorForm
     * @return
     */
    private static CryptoService getCryptoService(ValidatorForm validatorForm) {
        String plainText = null;
        CryptoService cryptoService = null;
        // 获取加密类型
        String encodeType = validatorForm.getEncodeType();
        if (StringUtil.hasText(encodeType)) {
            cryptoService =
                (CryptoService)SpringContextsUtil.getBean(encodeType + DecodeContants.DECODE_SERVICE_SUFFIX);
        } else {
            cryptoService = (CryptoService)SpringContextsUtil.getBean("AES" + DecodeContants.DECODE_SERVICE_SUFFIX);
        }
        return cryptoService;
    }

}
